package com.geline.easyexcel.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Excel列坐标工具
 *
 * @author: mengxin
 * @date: 2024/1/10 14:06
 */
public class ExcelColNumUtil {

    /**
     * 列转数字下标
     * @param col
     * @return
     */
    public static int colCodeToNum(String col) { //  "AAA"
        if (col == null)
            return -1;
        char[] chrs = col.toUpperCase().toCharArray(); // 转为大写字母组成的 char数组
        int length = chrs.length;
        int ret = -1;
        for (int i = 0; i < length; i++) {
            ret += (chrs[i] - 'A' + 1) * Math.pow(26, length - i - 1); // 当做26进制来算 AAA=111 26^2+26^1+26^0
        }
        return ret;// 702; 从0开始的下标
    }

    /**
     * 数字下标转列
     * @param index
     * @return
     */
    public static String numToColCode(int index) {
        int shang = index;
        int yu = 0;
        List<Integer> list = new ArrayList<Integer>(); // 10进制转26进制 倒序
        do
        {
            yu = shang % 26;
            shang = shang / 26;
            list.add(yu);
        }
        while (shang != 0);
        StringBuilder sb = new StringBuilder();
        for (int j = list.size() - 1; j >= 0; j--) {
            sb.append((char) (list.get(j) + 'A' - (j > 1 ? 1 : j)));     //倒序拼接  序号转字符 非末位 序号减去 1
        }
        return sb.toString();
    }
}
